package com.cn.yunhe.rentcars.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Paths;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller  
public class FileUploadController {  
   
	@Autowired
	private Environment env;
	  
    @RequestMapping(value="/uploadFile", method=RequestMethod.POST)  
    @ResponseBody
    public  String uploadFile( 
            @RequestParam("uploadfile") MultipartFile file){  
        if (!file.isEmpty()) {  
            try {  
              
                // Get the filename and build the local file path
                String filename = file.getOriginalFilename();
                String directory = env.getProperty("jkd.paths.uploadedFiles");
                String filepath = Paths.get(directory, filename).toString();
                
                // Save the file locally
                BufferedOutputStream stream =
                    new BufferedOutputStream(new FileOutputStream(new File(filepath)));
                stream.write(file.getBytes());
                stream.close();

                return "You successfully uploaded " + filename + " into " + filename + "-uploaded !";  
            } catch (Exception e) {  
                return "You failed to upload => " + e.getMessage();  
            }  
        } else {  
            return "You failed to upload because the file was empty.";  
        }  
    }  
   
} 